package miniologic

import (
	"context"
	"path/filepath"

	"go-zero-admin/apps/frame/storage/cmd/rpc/internal/svc"
	"go-zero-admin/apps/frame/storage/cmd/rpc/stopb"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/duke-git/lancet/v2/fileutil"
	"github.com/minio/minio-go/v7"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type AddFileAtMinioLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddFileAtMinioLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddFileAtMinioLogic {
	return &AddFileAtMinioLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddFileAtMinioLogic) AddFileAtMinio(in *stopb.AddFileAtMinioReq) (*stopb.AddFileAtMinioResp, error) {
	// 检验参数
	if err := l.valid(in); err != nil {
		return nil, err
	}

	// 文件地址
	bucketName := in.GetBucketName()
	filePath := in.GetFilePath()
	// 如果文件文字为空，则自己使用定义规则名称
	objectName := in.GetObjectName()
	if objectName == "" {
		objectName = objectName + l.svcCtx.SnowflakeNode.Generate().String()
		objectName = objectName + filepath.Ext(filePath)
	}
	contentType := fileutil.MiMeType(filePath)

	// 使用FPutObject上传文件。
	_, err := l.svcCtx.MinioClient.FPutObject(l.ctx, bucketName, objectName, filePath,
		minio.PutObjectOptions{ContentType: contentType})
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("上传失败"),
			tool.GetErrMsgFormat("insert minio file"), err, in)
	}

	return &stopb.AddFileAtMinioResp{NewFileName: objectName}, nil
}

// 校验参数
func (l *AddFileAtMinioLogic) valid(in *stopb.AddFileAtMinioReq) error {
	bucketName := in.GetBucketName()
	if bucketName == "" {
		return errors.Wrapf(xerr.NewErrMsg("上传失败：桶名不存在"),
			tool.GetErrMsgFormat("insert minio file"), "bucket name is not existed", in)
	}

	filePath := in.GetFilePath()
	if filePath == "" || !fileutil.IsExist(filePath) {
		return errors.Wrapf(xerr.NewErrMsg("上传失败：文件地址错误或不存在"),
			tool.GetErrMsgFormat("insert minio file"), "file path is not existed or error", in)
	}

	// 检查存储桶是否已经存在
	exists, err := l.svcCtx.MinioClient.BucketExists(l.ctx, bucketName)
	if err != nil {
		return errors.Wrapf(xerr.NewErrMsg("上传失败：检查桶是否存在失败"),
			tool.GetErrMsgFormat("insert minio file"), "check bucket is exist error", in)
	} else if !exists {
		err = l.svcCtx.MinioClient.MakeBucket(l.ctx, bucketName, minio.MakeBucketOptions{Region: in.GetLocation()})
		if err != nil {
			return errors.Wrapf(xerr.NewErrMsg("上传失败：创建桶失败"),
				tool.GetErrMsgFormat("insert minio file"), "create bucket error", in)
		}
	}

	return nil
}
